<template>
  <div>
    <!-- height="100%" height: 400px   arrow="always"-->
    <el-carousel height="400px" :autoplay="false" ref="carouselRef" @change="carouselChange">
      <el-carousel-item v-for="(item, index) in videos" :key="index">
        <video
          :src="item"
          style="width: 100%; height: 400px"
          :ref="(el) => getVideoRef(el, index)"
          controls
          preload="auto"
        ></video>
      </el-carousel-item>
    </el-carousel>
  </div>
</template>
<script setup>
import { ElCarousel, ElCarouselItem } from 'element-plus'
import Player from 'xgplayer'
import 'xgplayer/dist/index.min.css'
import { GetTop10ProblemVideosApi } from '@/api/screen'
import { onMounted, onUnmounted, ref, reactive, unref, nextTick } from 'vue'
const carouselRef = ref()
const videosRef = ref([])

const getVideoRef = (el, index) => {
  if (el) {
    videosRef.value[index] = el
  }
  // if (index == 0) {
  //   videosRef.value[0].addEventListener('load', () => {
  //     videosRef.value[0].play()
  //   })
  // }
}
const carouselChange = (e) => {
  // console.log('carouselChange-----', e)

  videosRef.value[e].play()
  videosRef.value[e].addEventListener('ended', function () {
    console.log('播放结束')
    if (e == videosRef.value.length - 1 && e != 0) {
      GetTop10ProblemVideo()
    }
    carouselRef.value.next()
  })
  videosRef.value.map((item, index) => {
    if (index != e) {
      item.pause()
    }
  })
}
const videos = ref([])
const GetTop10ProblemVideo = async () => {
  const res = await GetTop10ProblemVideosApi()
  // console.log('res-----', res.data)
  videos.value = res.data || []
  nextTick(() => {
    console.log('nextTick-----', videosRef.value[0])
    // videosRef.value[0].addEventListener('load', () => {
    //   videosRef.value[0].play()
    // })
    carouselChange(0)
  })
}
GetTop10ProblemVideo()

onUnmounted(() => {
  unref(carouselRef)?.destroy()
})
</script>
